﻿using CommonCore;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Common
{

    public class NpoiMemoryStream : MemoryStream
    {
        public NpoiMemoryStream()
        {
            AllowClose = true;
        }

        public bool AllowClose { get; set; }

        public override void Close()
        {
            if (AllowClose)
                base.Close();
        }
    }
    public static  class NOPIExcelHelper
    {
        /*
         * 使用：netFrameWork webAPI返回下发
            var ms = Utility.ListToExcel<DeviceSituationExcel>(list);
            result.Content = new StreamContent(ms);
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.ms-excel");
            result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
            result.Content.Headers.ContentDisposition.FileName = "设备运行统计" + DateTime.Now.ToString("yyyyMMdd") + ".xlsx";
         */
        public static MemoryStream ListToExcel<T>(List<T> data)
        {
            // 2007版本
            string sheetName = "sheet";
            bool isColumnWritten = true;
            IWorkbook workbook = new XSSFWorkbook();
            try
            {
                var sheet = workbook.CreateSheet(sheetName);

                ICellStyle s = workbook.CreateCellStyle();
                s.FillForegroundColor = HSSFColor.BlueGrey.Index;
                s.FillPattern = FillPattern.SolidForeground;



                var count = 0;
                var list = new List<string>();
                //标题
                PropertyInfo[] properties = typeof(T).GetProperties();
                if (isColumnWritten)
                {
                    var row = sheet.CreateRow(0);
                    for (int j = 0; j < properties.Count(); j++)
                    {
                        var item = properties[j];
                        var attrs = item.GetCustomAttributes(typeof(DisplayNameAttribute), true);
                        if (attrs != null && attrs.Count() > 0)
                        {
                            var displayName = ((DisplayNameAttribute)attrs[0]).DisplayName;
                            row.CreateCell(list.Count()).SetCellValue(displayName);
                            row.GetCell(list.Count()).CellStyle = s;
                            list.Add(item.Name);
                        }
                    }
                    count = 1;
                }
                else
                {
                    count = 0;
                }
                //数据
                for (var i = 0; i < data.Count; ++i)
                {
                    var itemData = data[i];
                    var row = sheet.CreateRow(count);
                    for (int iCell = 0; iCell < list.Count; iCell++)
                    {
                        var p = list[iCell];
                        var Properties = itemData.GetType().GetProperties().Where(c => c.Name == p).FirstOrDefault();
                        var value = Properties.GetValue(itemData)?.ToString();
                        row.CreateCell(iCell).SetCellValue(value);
                    }
                    ++count;
                }

                for (int columnNum = 0; columnNum <= list.Count; columnNum++)
                {
                    int columnWidth = sheet.GetColumnWidth(columnNum) / 256;//获取当前列宽度
                    for (int rowNum = 0; rowNum <= sheet.LastRowNum; rowNum++)//在这一列上循环行
                    {
                        IRow currentRow = sheet.GetRow(rowNum);
                        ICell currentCell = currentRow.GetCell(columnNum);
                        if (currentCell != null && !currentCell.ToString().IsNullOrEmpty())
                        {
                            int length = Encoding.UTF8.GetBytes(currentCell.ToString()).Length;//获取当前单元格的内容宽度
                            if (columnWidth < length + 1)
                            {
                                columnWidth = length + 1;
                            }//若当前单元格内容宽度大于列宽，则调整列宽为当前单元格宽度，后面的+1是我人为的将宽度增加一个字符
                        }

                    }
                    sheet.SetColumnWidth(columnNum, columnWidth * 256);
                }

                //写入到excel
                var ms = new NpoiMemoryStream();
                ms.AllowClose = false;
                workbook.Write(ms);
                ms.Flush();
                ms.Seek(0, SeekOrigin.Begin);
                ms.AllowClose = true;
                return ms;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
                return null;
            }
        }


        //使用：DataTable dt = resultList.ToDataTableNULL<SheetFile>();
        //      return File(ms, "application/vnd.ms-excel", "order.xlsx");
        public static DataTable ToDataTableComposeNULL<T>(this List<T> varlist)
        {
            DataTable dtReturn = new DataTable();
            // column names
            PropertyInfo[] oProps = null;
            // Could add a check to verify that there is an element 0
            foreach (T rec in varlist)
            {
                // Use reflection to get property names, to create table, Only first time, others will follow
                if (oProps == null)
                {
                    oProps = ((Type)rec.GetType()).GetProperties();
                    foreach (PropertyInfo pi in oProps)
                    {
                        Type colType = pi.PropertyType;
                        if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
                        {
                            colType = colType.GetGenericArguments()[0];
                        }
                        dtReturn.Columns.Add(new DataColumn(pi.Name, colType));
                    }
                }
                DataRow dr = dtReturn.NewRow(); foreach (PropertyInfo pi in oProps)
                {
                    dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue(rec, null);
                }
                dtReturn.Rows.Add(dr);
            }
            return (dtReturn);
        }



        #region Excel导入到Datable

        //string path = HttpContext.Current.Server.MapPath("/" + Guid.NewGuid().ToString() + ".xls");
        //if (postFile != null) postFile.SaveAs(path);
        //DataTable dt = ExcelHelper.ExcelToDataTable(path, true);

        /// <summary>
        /// Excel导入到Datable
        /// </summary>
        /// <param name="path"></param>
        /// <param name="isFirstRowColumn"></param>
        /// <returns></returns>
        public static DataTable ExcelToDataTable(string path, bool isFirstRowColumn)
        {
            ISheet sheet = null;
            DataTable data = new DataTable();
            IWorkbook workbook = null;
            int startRow = 0;

            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
            if (path.IndexOf(".xlsx") > 0) // 2007版本
                workbook = new XSSFWorkbook(fs);
            else if (path.IndexOf(".xls") > 0) // 2003版本
                workbook = new HSSFWorkbook(fs);

            sheet = workbook.GetSheetAt(0);
            if (sheet != null)
            {
                IRow firstRow = sheet.GetRow(0);
                int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数

                if (isFirstRowColumn)
                {
                    for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                    {
                        ICell cell = firstRow.GetCell(i);
                        if (cell != null)
                        {
                            string cellValue = cell.StringCellValue;
                            if (cellValue != null)
                            {
                                DataColumn column = new DataColumn(cellValue);
                                data.Columns.Add(column);
                            }
                        }
                    }
                    startRow = sheet.FirstRowNum + 1;
                }
                else
                {
                    startRow = sheet.FirstRowNum;
                }

                //最后一列的标号
                int rowCount = sheet.LastRowNum;
                for (int i = startRow; i <= rowCount; ++i)
                {
                    IRow row = sheet.GetRow(i);
                    if (row == null) continue; //没有数据的行默认是null　　　　　　　

                    DataRow dataRow = data.NewRow();
                    for (int j = row.FirstCellNum; j < cellCount; ++j)
                    {
                        if (row.GetCell(j) != null) //同理，没有数据的单元格都默认是null
                            dataRow[j] = row.GetCell(j).ToString();
                    }
                    data.Rows.Add(dataRow);
                }
            }

            System.IO.File.Delete(path);
            return data;
        }
        #endregion
    }
}
